package com.wmyg.scanninggun.utils;

import com.wmyg.scanninggun.bean.Bill;
import com.wmyg.scanninggun.message.BillRequest;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class BillChecker {

    public static boolean check(BillRequest bill) {
        ArrayList<String> qrs = new ArrayList<>();
        qrs.add(bill.getCaseId());
        for (String boxId : bill.getBoxes()) {
            qrs.add(boxId);
        }
        for (String qr : qrs) {
            if (!checkQr(qr)) {
                return false;
            }
        }
        if (!checkCase(bill.getCaseId())) {
            return false;
        }
        for (String box : bill.getBoxes()) {
            if (!checkBox(box)) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkSimply(Bill bill) {
        ArrayList<String> qrs = new ArrayList<>();
        qrs.add(bill.getCaseId());
        for (String boxId : bill.getBoxes()) {
            qrs.add(boxId);
        }
        for (String qr : qrs) {
            if (!checkQr(qr)) {
                return false;
            }
        }
        return true;
    }

    private static boolean checkQr(String qr) {
        return Pattern.matches("\\(01\\)[0-9]{14}\\(10\\)([0-9]|[A-Z]){6}\\(21\\)([0-9]|[A-Z]){16}", qr);
    }

    private static boolean checkCase(String qr) {
        return qr.substring(32, 33).equals("X");
    }

    private static boolean checkBox(String qr) {
        return qr.substring(32, 33).equals("H");
    }

    public static boolean checkBatch(BillRequest bill) {
        Set<String> batches = new HashSet<>();
        batches.add(bill.getCaseId().substring(22, 28));
        for (String box :
                bill.getBoxes()) {
            batches.add(box.substring(22, 28));
        }
        return batches.size() == 1;
    }
}
